/**
 * <strong>Title : ProductionOrderStatusController.java<br>
 * </strong> <strong>Package : cn.b.sky.mes.pp.controller<br>
 * </strong> <strong>Description : </strong>@类注释说明写在此处@<br>
 * <strong>Create on : 2015年10月13日 下午6:08:26<br>
 * </strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 *          <strong>修改历史:</strong><br>
 *          修改人 | 修改日期 | 修改描述<br>
 *          -------------------------------------------<br>
 * <br>
 * <br>
 */
package cn.b.sky.mes.pp.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.b.sky.mes.pp.enums.OrderStatusCode;
import cn.b.sky.mes.pp.model.condition.ProductionOrderCondition;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.b.sky.common.file.ExcelUtil;
import cn.b.sky.common.model.DWZResult;
import cn.b.sky.common.model.Page;
import cn.b.sky.user.SecurityContextUtil;
import cn.b.sky.user.controller.SecurityController;
import cn.b.sky.mes.cm.enums.ECodeEnums;
import cn.b.sky.user.service.ECodeService;
import cn.b.sky.user.service.model.ECode;
import cn.b.sky.mes.pp.constants.ProductConstant;
import cn.b.sky.mes.pp.model.OrderType;
import cn.b.sky.mes.pp.model.ProductionControl;
import cn.b.sky.mes.pp.model.ProductionOrder;
import cn.b.sky.mes.pp.service.OrderTypeService;
import cn.b.sky.mes.pp.service.ProductionControlService;
import cn.b.sky.mes.pp.service.ProductionOrderService;

import com.alibaba.fastjson.JSON;

/**
 * <strong>Title : ProductionOrderStatusController.java<br></strong>
 * <strong>Package : cn.b.sky.mes.pp.controller<br></strong>
 * <strong>Description : </strong>生产订单状态查询控制器<br> 
 * <strong>Create on : 2015年10月13日 下午6:08:26<br></strong>
 * <p>
 * @author dapeng.li<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人 | 修改日期 | 修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Controller
@RequestMapping(value = "productionOrderStatus")
@Slf4j
public class ProductionOrderStatusController extends SecurityController {

  @Resource
  ECodeService eCodeService;

  @Resource
  ProductionOrderService orderService;

  @Resource
  OrderTypeService orderTypeService;

  @Autowired
  ProductionControlService productionControlService;

  @RequestMapping(value = "orderStatusList")
  public String selectProductionOrderStatus(String navTabId,
                                            @ModelAttribute("condition") ProductionOrderCondition condition, Model model, HttpSession session) {

    List<ECode> ecode = eCodeService.selectECodeList(ECodeEnums.PRODUCTIONORDER_TYPE.getCode(),
        SecurityContextUtil.getLanguageCode());
    condition.setSiteCode(getSiteCode());
    if (StringUtils.isEmpty(condition.getMinRequirementDate()) || StringUtils.isEmpty(condition.getMaxRequirementDate())) {
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      condition.setMaxRequirementDate(sdf.format(new Date()));
      Date date = new Date();
      date.setTime(date.getTime() - 7 * 24 * 60 * 60 * 1000);
      condition.setMinRequirementDate(sdf.format(date));
    }
    Map orderStatusMap = orderService.getProductionOrdersStatus(condition, ecode);
    String orderStatusJSON = JSON.toJSONString(orderStatusMap);
    List<OrderType> orderTypes = orderTypeService.getAllOrderTypes(this.getSiteCode());
    model.addAttribute("orderTypeList", orderTypes);
    model.addAttribute("orderStatuseCode", ecode);
    model.addAttribute("orderStatusMap", orderStatusMap);
    model.addAttribute("orderStatusJSON", orderStatusJSON);
    session.setAttribute(ProductConstant.PRODUCTIONORDER_CONDITION, condition);
    return "pp/productionOrder/productionOrderStatus_list";
  }

  @RequestMapping(value = "viewProductionOrdersByStatus")
  public String viewProductionOrdersByStatus(@ModelAttribute("condition") ProductionOrderCondition condition,
      Model model, String status) {
    // 订单状态
    model.addAttribute(
        "ecodes",
        JSON.toJSONString(eCodeService.selectECodeList(ECodeEnums.PRODUCTIONORDER_TYPE.getCode(),
            SecurityContextUtil.getLanguageCode())));
    // 生产管理状态
    model.addAttribute("controlEcodes", JSON.toJSONString(eCodeService.selectECodeList(
        ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(), SecurityContextUtil.getLanguageCode())));
    model.addAttribute("condition", JSON.toJSONString(condition));
    model.addAttribute("status", status);
    return "pp/productionOrder/groupProductionOrders_list";
  }

  @RequestMapping(value = "getProductionOrdersByStatus")
  @ResponseBody
  public DWZResult getProductionOrdersByStatus(@ModelAttribute("condition") ProductionOrderCondition condition) {
    setCondition(condition);
    Page page = orderService.getProductionOrdersByCondition(condition);
    return ajaxDone(page);
  }

  @RequestMapping(value = "getProductionControlsByOrderNum")
  @ResponseBody
  public DWZResult getProductionControlsByOrderNum(String productionOrderNum) {
    List<ProductionControl> controls = productionControlService.selectProductionControlsByOrderNum(getSiteCode(),
        productionOrderNum);
    return ajaxDone(controls);
  }

  private void setCondition(ProductionOrderCondition condition) {
    condition.setSiteCode(getSiteCode());
    if (StringUtils.isEmpty(condition.getStatuseCode())) {
      condition.setStatuseCodes(new String[]{OrderStatusCode.CREATE.getValue(), OrderStatusCode.PLACE_ORDER.getValue()});
      condition.setPlannedendDateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    }
  }

  @RequestMapping(value = "exportOrdersToExcel")
  public void exportOrdersToExcel(HttpServletResponse response,
      @ModelAttribute("condition") ProductionOrderCondition condition) {
    setCondition(condition);
    Page page = orderService.getProductionOrdersByCondition(condition);
    List<ProductionOrder> orders = page.getData();
    setOrderStatusText(orders);
    Map<String, String> map = new LinkedHashMap<String, String>();

    String languageCode = SecurityContextUtil.getLanguageCode();
    String productionOrderReport = getImeViewMessageI18n(languageCode, "productionOrderReport.C");

    map.put("ProductionOrderNum", getImeViewMessageI18n(languageCode, "productionOrderNum.C"));
    map.put("statuseText", getImeViewMessageI18n(languageCode, "orderStatusECode.C"));
    map.put("materialCode", getImeViewMessageI18n(languageCode, "materialCode.C"));
    map.put("materialText", getImeViewMessageI18n(languageCode, "materialText.C"));
    map.put("plannedQuantity", getImeViewMessageI18n(languageCode, "plannedQuantity.C"));
    map.put("requirementDate", getImeViewMessageI18n(languageCode, "requirementDate.C"));
    map.put("productionLotNum", getImeViewMessageI18n(languageCode, "productionLotNum.C"));
    map.put("plannedstartDateTime", getImeViewMessageI18n(languageCode, "plannedstartDateTime.C"));
    map.put("plannedendDateTime", getImeViewMessageI18n(languageCode, "plannedendDateTime.C"));
    map.put("processCode", getImeViewMessageI18n(languageCode, "cmprocess_code.C"));
    map.put("CompletedQuantity", getImeViewMessageI18n(languageCode, "completedQuantity.C"));
    map.put("scrappedQuantity", getImeViewMessageI18n(languageCode, "scrappedQuantity.C"));
    map.put("repairQuantity", getImeViewMessageI18n(languageCode, "repairQuantity.C"));
    map.put("actualstartDateTime", getImeViewMessageI18n(languageCode, "actualstartDateTime.C"));
    map.put("actualendDateTime", getImeViewMessageI18n(languageCode, "actualendDateTime.C"));
    map.put("orderTypeCode", getImeViewMessageI18n(languageCode, "orderTypeCode.C"));
    map.put("orderTypeText", getImeViewMessageI18n(languageCode, "orderTypeText.C"));
    map.put("createUser", getImeViewMessageI18n(languageCode, "createUser.C"));
    map.put("createDateTime", getImeViewMessageI18n(languageCode, "createDateTime.C"));
    map.put("modifyUser", getImeViewMessageI18n(languageCode, "modifyUser.C"));
    map.put("modifyDateTime", getImeViewMessageI18n(languageCode, "modifyDateTime.C"));

    try {
      ExcelUtil.exportToExcel(response, productionOrderReport, map, orders);
    } catch (IOException e) {
      log.error("{}", e);
    }

  }

  @RequestMapping(value = "exportOrderControlsToExcel")
  public void exportOrderControlsToExcel(String productionOrderNum, HttpServletResponse response) {
    List<ProductionControl> controls = productionControlService.selectProductionControlsByOrderNum(getSiteCode(),
        productionOrderNum);

    String languageCode = SecurityContextUtil.getLanguageCode();
    if (!controls.isEmpty()) {
      setControlStatusText(controls);
    }

    Map<String, String> map = new LinkedHashMap<String, String>();
    map.put("productionControlNum", getImeViewMessageI18n(languageCode, "productionControlNum.C"));
    map.put("statuseText", getImeViewMessageI18n(languageCode, "controlStatus.C"));
    map.put("workCenterTypeText", getImeViewMessageI18n(languageCode, "workCenter_type.C"));
    map.put("workCenterCode", getImeViewMessageI18n(languageCode, "workCenterCode.C"));
    map.put("workCenterText", getImeViewMessageI18n(languageCode, "workCenterText.C"));
    map.put("plannedQuantity", getImeViewMessageI18n(languageCode, "plannedQuantity.C"));
    map.put("completedQuantity", getImeViewMessageI18n(languageCode, "completedQuantity.C"));
    map.put("scrappedQuantity", getImeViewMessageI18n(languageCode, "scrappedQuantity.C"));
    map.put("repairQuantity", getImeViewMessageI18n(languageCode, "repairQuantity.C"));
    map.put("actualstartDateTime", getImeViewMessageI18n(languageCode, "actualstartDateTime.C"));
    map.put("actualendDateTime", getImeViewMessageI18n(languageCode, "actualendDateTime.C"));
    map.put("processCode", getImeViewMessageI18n(languageCode, "cmprocess_code.C"));
    map.put("orderTypeCode", getImeViewMessageI18n(languageCode, "orderTypeCode.C"));
    map.put("orderTypeText", getImeViewMessageI18n(languageCode, "orderTypeText.C"));
    try {
      ExcelUtil.exportToExcel(response, getImeViewMessageI18n(languageCode, "productionControlReport.C")
          + productionOrderNum, map, controls);
    } catch (IOException e) {
      log.error("{}", e);
    }
  }

  private void setOrderStatusText(List<ProductionOrder> orders) {
    Map<String, String> statusMap = transEcodes2Map(eCodeService.selectECodeList(
        ECodeEnums.PRODUCTIONORDER_TYPE.getCode(), SecurityContextUtil.getLanguageCode()));
    for (ProductionOrder order : orders) {
      order.setStatuseText(statusMap.get(order.getStatuseCode()));
    }
  }

  private void setControlStatusText(List<ProductionControl> controls) {
    Map<String, String> statusMap = transEcodes2Map(eCodeService.selectECodeList(
        ECodeEnums.PRODUCTIONCONTROL_STATUS.getCode(), SecurityContextUtil.getLanguageCode()));
    for (ProductionControl control : controls) {
      control.setStatuseText(statusMap.get(control.getStatuseCode()));
    }
  }

  private Map<String, String> transEcodes2Map(List<ECode> eCodes) {
    Map<String, String> map = new HashMap<String, String>();
    for (ECode eCode : eCodes) {
      map.put(eCode.geteCode(), eCode.geteCodeText());
    }
    return map;
  }

}
